//
//  BaseObserved.swift
//  Robot
//
//  Created by ming on 2025/2/18.
//

import Foundation
import Combine

class BaseObserved<M: Codable>: ObservableObject {
    @Published var models: [M] = []
    @Published var show: Bool = false
    @Published var isEmpty: Bool = false
    @Published var page: Int = 0
    @Published var toast: String?
    lazy var cancellables = Set<AnyCancellable>()
    
    init() {
        self.loadDatas()
    }
    
    public func loadDatas() { }
}

extension BaseObserved where M: Identifiable {
    func listItemAppears(_ item: M) {
        if models.isLastItem(item) {
            self.loadDatas()
        }
    }
}

extension BaseObserved where M: SQLProtocol {
    func loadSQLData() {
        let size: Int = 20
        let page = self.models.count / size
        self.models.append(contentsOf: SQLManager.share.local.querys(page: page, size: size))
    }
    
    func delSQLData(model: M, value: Int) {
        SQLManager.share.local.delete(model: model, key: "id", value: value)
    }
    
    func addSQLData(model: M) {
        SQLManager.share.local.insert(model: model)
    }
    
    func isExist(key: String, value: String) -> Bool {
        let models: [M] = SQLManager.share.local.search(key: key, value: value, page: 0, limit: 1)
        return models.isEmpty
    }
    
    var allCount: Int {
        return SQLManager.share.local.count(M.table)
    }
}


